/*
 * @Author: wwssaabb
 * @Date: 2021-12-10 10:28:18
 * @LastEditTime: 2021-12-14 10:12:57
 * @FilePath: \handwritten-code\main\发布订阅模式.js
 */

/* 
发布订阅模式、事件总线
  - 事件管理，on、emit、off
*/

class EventEmitter{
  constructor(){
    this.cache={}
  }

  //注册事件
  on(name,callback){
    this.cache[name]?this.cache[name].push(callback):this.cache[name] = [callback]
  }

  //执行事件
  emit(name,...args){
    if(this.cache[name]){
      this.cache[name].forEach(fn=>fn(...args))
    }
  }

  //注销事件
  off(name){
    if(this.cache[name]){
      delete this.cache[name]
    }
  }
}

// 测试
let eventBus = new EventEmitter()
let fn1 = function (name, age) {
  console.log(`${name} ${age}`)
}
let fn2 = function (name, age) {
  console.log(`hello, ${name} ${age}`)
}
eventBus.on('aaa', fn1)
eventBus.on('aaa', fn2)
eventBus.emit('aaa', '布兰', 12)



class EventEmitter{
  constructor(){
    this.cache={}
  }

  //注册事件
  on(name,callback){
    this.cache[name]?this.cache[name].push(callback):this.cache[name] = [callback]
  }

  //执行事件
  emit(name,...args){
    if(this.cache[name]){
      this.cache[name].forEach(fn=>fn(...args))
    }
  }

  //注销事件
  off(name){
    if(this.cache[name]){
      delete this.cache[name]
    }
  }
}